package com.wkk.yuli.job;

import com.alibaba.fastjson.JSONObject;
import com.wkk.utils.DateUtils;
import com.wkk.yuli.bo.Disappear;
import com.wkk.yuli.core.Container;
import com.wkk.yuli.util.ToolUtils;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import java.util.Iterator;
import java.util.Map;

/**
 * @author : WangKeKe
 * @date : 2020/9/25 9:51
 * Description :
 */

@Slf4j
public class RemoveInvalidKeyJob implements Job {

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        if (Container.getYuLi().size() == 0) {
            log.info("里面没有内容 无需执行" + DateUtils.getTimestamp());
        } else {
            log.info(" 失效key移除任务  时间:" + DateUtils.getTimestamp() + "任务执行");
            for (Iterator<Map.Entry<Object, Object>> it = Container.getYuLi().entrySet().iterator(); it.hasNext(); ) {
                Map.Entry<Object, Object> item = it.next();
                log.info("key为：" + item.getKey() + "是否存活");
                // = 如果过期则移除
                Disappear disappear = JSONObject.parseObject((String) Container.getYuLi().get(item.getKey()), Disappear.class);
                Long disappearTime = disappear.getExpireTime();
                Long systemTime = System.currentTimeMillis();
                if (disappearTime != -1L && disappearTime - systemTime <= 0) {
                    it.remove();
                    log.info("key为：" + item.getKey() + "判定为--失效--已移除");
                } else {
                    log.info("key为：" + item.getKey() + "判定为--存活");
                }
            }
            // 执行持久化
            ToolUtils.pushTime();
            log.info(" 失效key移除任务  时间:" + DateUtils.getTimestamp() + "任务结束");
        }
    }
}
